﻿using DKPScoreWebApi.Data;
using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace DKPScoreWebApi.Services.Implementations
{
    public class MemberService : IMemberService
    {
        private readonly AppDbContext _context;
        private readonly ILogger<MemberService> _logger;

        public MemberService(AppDbContext context, ILogger<MemberService> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<GuildMember> AddGuildMemberAsync(int guildId, AddMemberRequest request)
        {
            // 检查成员是否已存在
            var existingMember = await _context.GuildMembers
                .FirstOrDefaultAsync(m => m.GuildId == guildId && m.Name == request.Name);

            if (existingMember != null)
            {
                if (!existingMember.IsActive)
                {
                    // 重新激活已存在的成员
                    existingMember.IsActive = true;
                    existingMember.CharacterClass = request.CharacterClass;
                    existingMember.Role = request.Role;
                    existingMember.CharacterLevel = request.CharacterLevel ?? 1;
                    existingMember.JoinDate = DateTime.Now;

                    await _context.SaveChangesAsync();
                    return existingMember;
                }
                throw new ArgumentException("成员名称已存在");
            }

            var member = new GuildMember
            {
                GuildId = guildId,
                Name = request.Name,
                CharacterClass = request.CharacterClass,
                Role = request.Role,
                CharacterLevel = request.CharacterLevel ?? 1,
                JoinDate = DateTime.Now,
                CreatedAt = DateTime.Now
            };

            _context.GuildMembers.Add(member);
            await _context.SaveChangesAsync();

            _logger.LogInformation("向工会 {GuildId} 添加成员 {MemberName}", guildId, request.Name);
            return member;
        }

        public async Task<List<GuildMember>> GetGuildMembersAsync(int guildId, bool activeOnly = true)
        {
            var query = _context.GuildMembers
                .Where(m => m.GuildId == guildId);

            if (activeOnly)
                query = query.Where(m => m.IsActive);

            return await query
                .OrderBy(m => m.Name)
                .ToListAsync();
        }

        public async Task<GuildMember> GetMemberByIdAsync(int memberId)
        {
            return await _context.GuildMembers
                .Include(m => m.Guild)
                .Include(m => m.PointRecords)
                .ThenInclude(pr => pr.PointItem)
                .FirstOrDefaultAsync(m => m.Id == memberId);
        }

        public async Task<bool> UpdateMemberAsync(int memberId, AddMemberRequest request)
        {
            var member = await _context.GuildMembers.FindAsync(memberId);
            if (member == null)
                return false;

            member.Name = request.Name;
            member.CharacterClass = request.CharacterClass;
            member.Role = request.Role;
            member.CharacterLevel = request.CharacterLevel ?? member.CharacterLevel;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> RemoveGuildMemberAsync(int guildId, int memberId)
        {
            var member = await _context.GuildMembers
                .FirstOrDefaultAsync(m => m.Id == memberId && m.GuildId == guildId);

            if (member == null)
                return false;

            member.IsActive = false;
            await _context.SaveChangesAsync();

            _logger.LogInformation("从工会 {GuildId} 移除成员 {MemberName}", guildId, member.Name);
            return true;
        }

        public async Task<bool> RestoreGuildMemberAsync(int guildId, int memberId)
        {
            var member = await _context.GuildMembers
                .FirstOrDefaultAsync(m => m.Id == memberId && m.GuildId == guildId);

            if (member == null)
                return false;

            member.IsActive = true;
            await _context.SaveChangesAsync();

            return true;
        }

        public async Task<List<GuildMember>> SearchMembersAsync(int guildId, string searchTerm)
        {
            if (string.IsNullOrWhiteSpace(searchTerm))
                return await GetGuildMembersAsync(guildId);

            return await _context.GuildMembers
                .Where(m => m.GuildId == guildId &&
                           m.IsActive &&
                           (m.Name.Contains(searchTerm) ||
                            m.CharacterClass.Contains(searchTerm) ||
                            m.Role.Contains(searchTerm)))
                .OrderBy(m => m.Name)
                .ToListAsync();
        }
    }
}
